package com.sixuan.rabbitmqconsumer.workmode.workqueues;

import com.rabbitmq.client.*;

import java.io.IOException;


/**
 * RabbitMq工作模式：Work Queues
 * Created by LENOVO on 2020-7-8 15:59
 *
 * @author LENOVO
 */
public class WorkQueuesConsumer2 {
    private static final String rabbitMqHost = "47.97.195.191";
    private static final int rabbitMqPort = 5672;
    private static final String username = "guest";
    private static final String password = "guest";

    private static final String QUEUE_NAME = "WorkQueuesQueue";

    public static void main(String[] args) throws Exception {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(rabbitMqHost);
        connectionFactory.setPort(rabbitMqPort);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        connectionFactory.setVirtualHost("/");
        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();

        //声明队列
        channel.queueDeclare(QUEUE_NAME, true, false, false, null);

        //接收到消息后的执行方法
        DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //交换机
                String exchange = envelope.getExchange();
                long deliveryTag = envelope.getDeliveryTag();
                String message = new String(body, "utf-8");
                System.out.println("Received from provider : " + message);
            }
        };
        //监听消息basicConsume
        channel.basicConsume(QUEUE_NAME, true, defaultConsumer);
    }
}
